<template>
  <div ref="modal">
    <a-modal :getContainer="() => $refs.modal" :visible="visible" :title="modalTitle" width="760px" @cancel="handleCancel" @ok="handleOk">
      <div class="horizontalLayout">
        <DynamicForm :config="dyConfig" :questions="dyQuestions" ref="dynamicForm" class="dynamicForm">
          <template #generateCode>
            <a-input v-model:value="permissionEncoding" disabled></a-input>
          </template>
        </DynamicForm>

        <div class="collapse title-required">文件权限</div>
        <div class="form-tree-container">
          <div class="left">
            <div>
              <!-- <span class="collapse">文件权限编码</span> -->
              <a-tree
                v-if="state.treeData.length"
                v-model:checkedKeys="state.checkedKeys"
                checkable
                default-expand-all
                :tree-data="state.treeData"
                :disabled="state.isDisabled"
                @check="selectChecked"
              />
            </div>

            <!-- <div>
              <div class="transition" @click="state.showSecuritySelect = !state.showSecuritySelect">
                <span class="ant-tree-switcher ant-tree-switcher_open">
                  <span role="img" aria-label="caret-down" class="anticon anticon-caret-down ant-tree-switcher-icon">
                    <svg focusable="false" class="" data-icon="caret-down" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="0 0 1024 1024">
                      <path d="M840.4 300H183.6c-19.7 0-30.7 20.8-18.5 35l328.4 380.8c9.4 10.9 27.5 10.9 37 0L858.9 335c12.2-14.2 1.2-35-18.5-35z"></path>
                    </svg>
                  </span>
                </span>
                <span class="collapse">保密等级权限</span>
              </div>
              <a-checkbox-group v-show="state.showSecuritySelect" v-model:value="state.securityLevel" class="security-check" :disabled="state.isDisabled">
                <a-row>
                  <a-col :span="24">
                    <a-checkbox value="1">绝密</a-checkbox>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="24">
                    <a-checkbox value="2">机密</a-checkbox>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="24">
                    <a-checkbox value="3">秘密</a-checkbox>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="24">
                    <a-checkbox value="4">公开</a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
            </div> -->
          </div>

          <div class="right">
            <a-checkbox-group v-model:value="state.optPermisson" class="opt-check" :disabled="state.isDisabled">
              <a-row>
                <a-col :span="24">
                  <a-checkbox value="1">预览</a-checkbox>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-checkbox value="2">下载</a-checkbox>
                </a-col>
              </a-row>
            </a-checkbox-group>
          </div>
        </div>
      </div>

      <template #footer>
        <section class="footer-buttonGroups">
          <a-button type="info" @click="handleCancel">取消</a-button>
          <a-button type="primary" @click="handleOk" v-if="state.showType === 'ADD' || state.showType === 'UPDATE'">确定</a-button>
          <a-button type="primary" @click="handleEdit" v-if="state.showType === 'VIEW'">编辑</a-button>
        </section>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { DynamicForm } from '@/components/public-template';
import { treeFindById } from '@/components/public-template/publicMethod';
import indexService from './addDialog.service';
import { message } from 'ant-design-vue';
import { orgTreeData } from '@/config/api/system';
import { Api, fileTypeTree, generateCode, roleList, commonFilePermissionSave } from '@/config/api/fileAuthority';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  showType: {
    type: String,
    default: 'ADD'
  },
  detailId: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['update:visible', 'update:showType', 'refresh']);
const state = reactive({
  optPermisson: [], // 预览下载功能
  treeData: [],
  checkedKeys: [], // 树选中项
  isDisabled: false, // 是否禁用
  showType: props.showType,
  showSecuritySelect: true
});
// 弹窗标题
const modalTitle = props.showType == 'ADD' ? '添加文件权限' : props.showType == 'VIEW' ? '文件权限详情' : '编辑文件权限';
const dynamicForm = ref(null);
let permissionEncoding = ref<string>('');

const dyQuestions = reactive(indexService.getQuestions());
const dyConfig: any = {
  queryUrl: state.showType === 'ADD' ? '' : Api.commonFilePermissionGet,
  protType: state.showType === 'ADD' ? '' : 'get',
  urlName: state.showType === 'ADD' ? '' : props.detailId,
  noGetDataParams: state.showType === 'ADD' ? false : true,
  grid: 12,
  labelCol: 12,
  wrapperCol: 24,
  layout: 'vertical',
  cancelSave: true,
  beforeWithMethod(data) {
    for (let i of dyQuestions) {
      for (let j in data) {
        if (i.key === j) {
          i.value = data[j];
        }
      }
    }
    permissionEncoding.value = data['code']; // 文件权限编码处理

    // 文件类型权限处理
    state.checkedKeys = [];
    data['directories'].map((item) => {
      state.checkedKeys.push(item.id);
    });
    console.log(state.checkedKeys, 1111);
    // 角色处理
    dyQuestions[2].value = [];
    data['roles'].map((item) => {
      dyQuestions[2].value.push(item.roleId);
    });
    state.optPermisson = data['optPermisson'].split(','); // 预览下载处理
  }
};

onMounted(() => {
  getTypeTree();

  if (state.showType === 'ADD') {
    getGenerateCode();
  }

  if (state.showType === 'VIEW') {
    // 组件禁用状态
    state.isDisabled = true;
    for (let i of dyQuestions) {
      i.disabled = true;
    }

    const time = setTimeout(() => {
      dynamicForm.value.getData();
      clearTimeout(time);
    }, 1000);
  }
});

// 获取树型显示数据
const getTypeTree = () => {
  fileTypeTree({}).then((res) => {
    res.data = res.data.map((obj) => ({ ...obj, checkable: true }));
    console.log(res.data, 'res.data');
    res.data = [{ name: '文件类型权限', children: res.data, checkable: false }];
    let changeData = JSON.stringify(res.data);
    changeData = changeData.replace(/id/gi, 'key');
    changeData = changeData.replace(/name/gi, 'title');
    state.treeData = [...JSON.parse(changeData)];
  });
};

// 获取档案权限编码
const getGenerateCode = () => {
  generateCode({ type: 'DMSFT01' }).then((res) => {
    if (res && res.success) {
      permissionEncoding.value = res.data[0];
    }
  });
};

// 点击添加文件权限时触发
const handleOk = () => {
  dyQuestions[0].value = permissionEncoding.value; // 文件权限编码赋值
  dynamicForm.value.getData();

  dynamicForm.value.onFinish(async (data) => {
    let checkedKeys, preview;
    checkedKeys = state.checkedKeys;
    preview = state.optPermisson.join(',');
    for (let i in data) {
      if (i === '') {
        delete data[i];
      }
    }
    data = JSON.parse(JSON.stringify(data).replace(/dept/i, 'roles'));
    // 编辑保存操作
    if (state.showType === 'UPDATE') {
      data['id'] = props.detailId;
    }
    const res = await orgTreeData({});
    if (res && res.success) {
      data['roles'].map((item, index) => {
        const obj = treeFindById(res.data, item, 'childOrg');
        data['roles'][index] = { roleId: obj.id, roleName: obj.name }; // 角色赋值
      });
      console.log(data['roles'], 666);
      if (state.checkedKeys.length <= 0) {
        message.error('文件类型权限至少选择一项');
        return;
      } else if (state.optPermisson.length <= 0) {
        message.error('预览下载至少选择一项');
        return;
      }
      commonFilePermissionSave({
        ...data,
        directoryIds: checkedKeys,
        optPermisson: preview
      }).then((res) => {
        if (res && res.success) {
          message.success(res.message);
          emit('refresh');
          emit('update:visible', false);
        }
      });
    }
  });
};

const handleCancel = () => {
  emit('update:visible', false);
};

const handleEdit = () => {
  state.isDisabled = false;
  for (let i of dyQuestions) {
    i.disabled = false;
  }
  state.showType = 'UPDATE';
};

const selectChecked = (checkedKeys, { checked, checkedNodes, node, event }) => {
  if (checkedKeys == '0-0') {
    return;
  }
  // 标签选中状态
  if (checked) {
    // 树选择没有选中标签key值的情况
    if (!state.checkedKeys.includes(checkedKeys.join(''))) {
      let arr = []; // 存放所有叶子节点
      if (node.children && node.children.length) {
        for (let i of fn(node.children)) {
          arr.push(i.key);
        }
      }
      if (arr.length) {
        state.checkedKeys = state.checkedKeys.concat(arr);
      } else {
        state.checkedKeys = state.checkedKeys.concat(checkedKeys);
      }
    }
  }
};

// 递归树children
const fn = (arr) => {
  const res = [];
  res.push(...arr);
  for (const item of arr) {
    if (item.children && item.children.length) {
      res.push(...fn(item.children));
    }
  }
  return res;
};
</script>

<style lang="less" scoped>
.horizontalLayout {
  min-height: 60vh;
  .dynamicForm {
    flex-basis: 50%;
  }
}
:deep(.ant-modal-body) {
  .collapse {
    margin-left: 4px;
    display: block;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.65);
    line-height: 24px;
    margin-bottom: 5px;
  }
  .title-required::before {
    display: inline-block;
    margin-right: 4px;
    color: #ff4d4f;
    font-size: 14px;
    font-family: SimSun, sans-serif;
    line-height: 1;
    content: '*';
  }
  .opt-check {
    .ant-row {
      margin-bottom: 5px;
    }
  }
  .form-tree-container {
    display: flex;
    border-radius: 6px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    flex: 1;
    .ant-tree .ant-tree-list .ant-tree-node-content-wrapper {
      padding: 0;
    }
    .left {
      flex: 1;
      padding: 10px;
      border-right: 1px solid rgba(0, 0, 0, 0.15);
      .transition {
        display: flex;
      }
      .security-check {
        margin-left: 47px;
        .ant-row {
          margin-bottom: 5px;
        }
      }
    }
    .right {
      flex: 1;
      padding: 10px;
    }
  }
}
:deep(.ant-tree-list) {
  .ant-tree-title {
    display: block;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.65);
    line-height: 24px;
  }
}

.footer-buttonGroups {
  display: flex;
  justify-content: center;

  & > button:not(:first-child) {
    margin-left: 20px;
  }
}
</style>
